/*
 * Guild Fraktion Info (GFI)
 * Version 1.2
 * @requires jQuery v1.8.x
 * @requires jQuery Tablesorter v2.0 (jaxid corrected version)
 * 
 * Copyright (c) 2012-2013 Marantis (www.marantis.de)
 * 
 * Examples and docs at: http://tablesorter.com
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
 */

//-----------------------------------------------------------------------------------------------------------------
/*
 * Change this to your own GFI JSON RESULT (gfi scan server)
 */
var SERVER_URL = "http://server01.jaxid.com/gfi/gfi-export.json?callback=?";

/*
 * Different filter base/limit definitions
 */
var GUILD_LEVEL_BASE = 0;
var REPUTATION_LEVEL_BASE = 0;
var REPUTATION_LEVEL_MAX = 7;

/*
 * Cache for the GFI JSON / RESULT TABLE datas
 */
var JSON_RETURN;
var TABLE_ROW_LIST;

/*
 * Your wow armory url (required for the 
 * character url in the result table)
 */
var ARMORY_URL ="http://eu.battle.net/wow/de/character";

/*
 * The name of your realm (required for the 
 * character url in the result table)
 */
var REALM_NAME = "gilneas";

//-----------------------------------------------------------------------------------------------------------------
/*
 * Called from the button in the html page
 */
function loadGfiJson(){
    callJsonResult();
}

//-----------------------------------------------------------------------------------------------------------------
/*
 * *** JSON-P SERVER CALL ***
 */
function callJsonResult(){
    var jsonUrl = SERVER_URL;
    $.getJSON(jsonUrl);
}

//-----------------------------------------------------------------------------------------------------------------
/*
 * *** SERVER RETURNED RESULT ***
 */
function gfiResult(jsonObj){
    if (jsonObj == null)
        return;
    
    JSON_RETURN = jsonObj;
    TABLE_ROW_LIST = convertJson2RowList(jsonObj);
    
    if (JSON_RETURN != null){
        $("#idLoadGfiDataDiv").hide();
        $("#idGfiDataResultDiv").show();

        fillTable();
    } else {
        var msg = "Unable to load the GFI data!";
        $("#idLoadGfiDataDiv").html("<h3>" + msg + "</h3>")
        alert(msg)
    }
    
}

//-----------------------------------------------------------------------------------------------------------------
/*
 * Fill the result table with the GFI datas
 */
function fillTable(){
    if (TABLE_ROW_LIST == null)
        return;
    
    //*** tabelle löschen ***
    var resultTable = $("#idResultTable");
    $.tablesorter.clearTableBody(resultTable);
    
    //*** tabelle füllen ***
    var rowCounter = 0;
    var resultTableBody = $("#idResultTableBody");
    
    $.each(TABLE_ROW_LIST, function(idx, row){
        
        if (filterGfiRow(row)){
            return;
        }
        
        addRow2Table(row, resultTableBody);
        rowCounter += 1;
    });
    
    $("#idResultTable").trigger("update");
    $("#idResultTable").tablesorter( {
        sortList: [[4,1],[0,0]]
    } );
    
    var rowCountComplete = JSON_RETURN.gfiData.guildMembers.length;
    var txtStatus = " Member: " + rowCounter + " / " + rowCountComplete;
    $("#labRowCounter").html(txtStatus);
    
}

//-----------------------------------------------------------------------------------------------------------------
/*
 * Take just the required infos from the gfi json list 
 * to the table row array
 */
function convertJson2RowList(jsonObj){
    
    var rowItem = new Array();
    var rowList = new Array();
    
    var guildLevelNames = jsonObj.gfiData.guildLevelNames;
    var guildMembers = jsonObj.gfiData.guildMembers;
    
    $.each(guildMembers, function(idx, gfiRow){
        
        var rowItem = new Array();
        
        //*** character name ***
        rowItem[0] = gfiRow.charName;
        
        //*** character level ***
        rowItem[1] = string2Integer(gfiRow.charLevel);
        
        //*** item level ***
        rowItem[2] = string2Integer(-1);
        if (gfiRow.itemLevel != null){
            
            var iLvLAverage = gfiRow.itemLevel.averageItemLvl;
            iLvLAverage = string2Integer(iLvLAverage);
            if (iLvLAverage == null){
                iLvLAverage = 0;
            }
            
            var iLvLEquipped = gfiRow.itemLevel.equippedItemLvl;
            iLvLEquipped = "0." + iLvLEquipped;
            iLvLEquipped = string2Float(iLvLEquipped);
            if (iLvLEquipped == null){
                iLvLEquipped = 0;
            }
            
            var iLvLNumber = iLvLAverage + iLvLEquipped;
            rowItem[2] = iLvLNumber;
        }

        //*** guild rank ***
        var guildRank = string2Integer(gfiRow.guildRank);
        rowItem[3] = guildRank;
        if (guildLevelNames != null){
            var guildRankText = "(" + (guildRank + GUILD_LEVEL_BASE) + ") ";
            guildRankText += guildLevelNames[guildRank];
            rowItem[4] = guildRankText;
        }
        
        //*** guild reputation ***
        if (gfiRow.guildReputation != null){
            var repLevel = string2Integer(gfiRow.guildReputation.rep);
            rowItem[5] = repLevel;
            rowItem[6] = "(" + repLevel + ") " + getReputationTitle_EN(repLevel)
        }else{
            if (gfiRow.charLevel < 10){
                rowItem[5] = -1;
                rowItem[6] = "(-1) Level < 10";
            }else{
                rowItem[5] = -2;
                rowItem[6] = "(-2) | Error";
            }
        }
        
        rowList[idx] = rowItem;
    });
    
    return rowList;
}

//-----------------------------------------------------------------------------------------------------------------
/*
 * Add a single row to the table
 */
function addRow2Table(row, tableBody){
    
    if (row == null || tableBody == null)
        return;
    
    var aTR = document.createElement('tr');

    var guildLevel = 0;
    var repLevel = 0;
    
    $.each(row, function(col, value){

        if (col == 0){ // character name as armory url
            var aTDChar = createTDArmoryCharacterUrl(value);
            aTR.appendChild(aTDChar);
        
        } else if (col == 3){ // is the guild level (not to show, but to save)
            guildLevel = value;
            
        } else if (col == 5) { // is the reputation level (not to show, but to save)
            repLevel = value;
            
        } else{
            var aTD = createTD(value);
            
            if (col == 6){ // set the BG color for this reputation
                aTD.className = "repNr" + repLevel;
            }
            
            aTR.appendChild(aTD);
        }
        
    });
    
    tableBody.append(aTR);
}

//-----------------------------------------------------------------------------------------------------------------
/*
 * Create a single HTML TD TAG for the result table row
 */
function createTD(value){
    var aTD = document.createElement('td');
    var tdText = document.createTextNode(value);
    if (tdText == null || tdText.length <= 0){
        tdText = "&#160;";
        
    }
    
    aTD.appendChild(tdText);
    return aTD;
}

//-----------------------------------------------------------------------------------------------------------------
/*
 * Create a single HTML URL TD TAG for the result table row
 */
function createTDArmoryCharacterUrl(characterName){
    //*** create the TD tag ***
    var aTD = document.createElement('td');

    //*** create the A (link) tag ***
    var charUrl = document.createElement('a');

    //*** define the HREF (target link) attribute ***
    var charUrlHref = document.createAttribute("href");
    var armoryUrl = ARMORY_URL + "/" + REALM_NAME + "/"  + characterName + "/simple";
    charUrlHref.nodeValue = armoryUrl;
    charUrl.setAttributeNode(charUrlHref);
    
    //*** define the TARGET (blank = new page) attribute ***
    var charUrlTarget = document.createAttribute("target");
    charUrlTarget.nodeValue = "_blank";
    charUrl.setAttributeNode(charUrlTarget);
    
    //*** define the link text (= character name) ***
    if (characterName == null || characterName.length <= 0){
        characterName = "&#160;";
    }
    
    var charUrlText = document.createTextNode(characterName);
    charUrl.appendChild(charUrlText);
    
    //*** add the A tag to the TD tag ***
    aTD.appendChild(charUrl);
    return aTD;
}

//-----------------------------------------------------------------------------------------------------------------
/*
 * Localization: Reputation title in german language
 */
function getReputationTitle_DE(repLevel){

    switch (repLevel) {
        case -2:
            return "fehler";
        case -1:
            return "undefiniert";
        case 0:
            return "hasserfüllt";
        case 1:
            return "feindselig";
        case 2:
            return "unfreundlich";
        case 3:
            return "neutral";
        case 4:
            return "freundlich";
        case 5:
            return "wohlwollend";
        case 6:
            return "respektvoll";
        case 7:
            return "ehrfürchtig";
        default:
            return "undefiniert";
    }
}

//-----------------------------------------------------------------------------------------------------------------
/*
 * Localization: Reputation title in english language
 */
function getReputationTitle_EN(repLevel){

    switch (repLevel) {
        case -2:
            return "error";
        case -1:
            return "undefined";
        case 0:
            return "hated";
        case 1:
            return "hostile";
        case 2:
            return "unfriendly";
        case 3:
            return "neutral";
        case 4:
            return "friendly";
        case 5:
            return "honoured";
        case 6:
            return "revered";
        case 7:
            return "exalted";
        default:
            return "undefined";
    }
}

//-----------------------------------------------------------------------------------------------------------------
/*
 * Check if the selected filter does exist.
 */
function checkFilter(){
    
    var selected = $("#optGMemberFilter option:selected");
    var filterNumber = selected.val();
    if (!$.isNumeric(filterNumber)){
        return false;
    } else if (filterNumber == 0){
        return true;
    } else if (filterNumber == 1){
        var filterRepList = JSON_RETURN.gfiData.guildReputationFilter;
        if (filterRepList == null){
            var errMsg1 = "Reputation filter is undefined!\n\nYou have to define the filter by the ";
            errMsg1 += "GFI server tool in the 'gfi-condig-properties' file."
            alert(errMsg1);
            return false;
        } else {
            return true;
        }
    } else if (filterNumber == 2){
        var guildRankList = JSON_RETURN.gfiData.guildLevelFilter;
        if (guildRankList == null){
            var errMsg2 = "Guild rank filter is undefined!\n\nYou have to define the filter by the ";
            errMsg2 += "GFI server tool in the 'gfi-condig-properties' file."
            alert(errMsg2);
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

//-----------------------------------------------------------------------------------------------------------------
/*
 * Filter management for a table row
 */
function filterGfiRow(row){
    
    var selected = $("#optGMemberFilter option:selected");
    var filterNumber = selected.val();
    if (!$.isNumeric(filterNumber) || filterNumber == 0){
        return false;
    } else if (filterNumber == 1){
        var filterFlag = filterGuildReputation(row);
        if (filterFlag){
            return true;
        }
    } else if (filterNumber == 2){
        var filterFlag = filterGuildLevel(row);
        if (filterFlag){
            return true;
        }
    }
    
    //*** when we are here then the row is not to filter ***
    return false;
}

//-----------------------------------------------------------------------------------------------------------------
/*
 * Which guild rank is to HIGH?
 * 
 * a guild member with the guild reputation level 'honoured' (6)
 * should has (minimum) the guild level 'member' (4)
 */
function filterGuildLevel(row){

    if (row == null){
        return true;
    }
    
    var charGRank = row[3];
    var charGRep = row[5];

    /*
     * if the guild reputation < 0 (error or char lvl < 10)
     * then don't show the char row.
     */
    if (charGRep < 0){
        return true;
    }
    
    var filterRankList = JSON_RETURN.gfiData.guildLevelFilter;
    if (filterRankList == null){
        return true;
    }
    
    var result = true;

    $.each(filterRankList, function(filterGRank, filterGRep){
        
        /*
         * if just 1 check brings the result to show the row (filter == false)
         * then an other check is not required anymore
         */
        if (!result){
            return;
        }
        
        filterGRank = string2Integer(filterGRank);
        filterGRep = string2Integer(filterGRep);

        /*
         * does exist a filter for the guild rank?
         */
        if (charGRank == filterGRank){
            
            /*
             * higher guild reputation number means a lower rank!
             * 
             * if the character has a smaller reputation than in the filter
             * then the character should be shown (for a correction)
             */
            if (charGRep < filterGRep){
                result = false;
            }
        }
    });
    
    return result;

}
    
//-----------------------------------------------------------------------------------------------------------------
/*
 * Which guild rank is to LOW?
 * 
 * a guild member with the guild reputation level 'honoured' (6)
 * should has (minimum) the guild level 'member' (4)
 */
function filterGuildReputation(row){
    
    if (row == null){
        return true;
    }
    
    var charGRank = row[3];
    var charGRep = row[5];
    
    var filterRepList = JSON_RETURN.gfiData.guildReputationFilter;
    if (filterRepList == null){
        return true;
    }
    
    var result = true;

    $.each(filterRepList, function(filterGRep, filterGRank){
        
        /*
         * if just 1 check brings the result to show the row (filter == false)
         * then an other check is not required anymore
         */
        if (!result){
            return;
        }
        
        filterGRep = string2Integer(filterGRep);
        filterGRank = string2Integer(filterGRank);

        /*
         * if the character has the same or an higer reputation 
         * than the filter has to check the guild level.
         */
        if (charGRep >= filterGRep){
            
            /*
             * lower guild level number means a higher rank!
             * 
             * if the character has a greater rank than the filter
             * then the character should be shown (for a correction)
             */
            if (charGRank > filterGRank){
                result = false;
            }
        }
    });
    
    return result;
}

//-----------------------------------------------------------------------------------------------------------------
/*
 * Common convert function
 */
function string2Integer(val){
    if (val == null) {
        return null;
    } else if (typeof val == "number") {
        return val;
    } else if (typeof val == "string") {
        return parseInt(val);
    } else {
        return null;
    }
}

/*
 * Common convert function
 */
function string2Float(val){
    if (val == null) {
        return null;
    } else if (typeof val == "number") {
        return val;
    } else if (typeof val == "string") {
        return parseFloat(val);
    } else {
        return null;
    }
}


//-----------------------------------------------------------------------------------------------------------------
/*
* Event handler for the guild member filter
*/
$("#optGMemberFilter").change(function(){
    if (JSON_RETURN == null){
        loadGfiJson();
    }else if (!checkFilter()){
        return;
    }else{
        fillTable();
    }
});


//-----------------------------------------------------------------------------------------------------------------
$(document).ready(function(){ 
    $("#idGfiDataResultDiv").hide();
    $("#idResultTable").tablesorter();
    if (JSON_RETURN == null){
        loadGfiJson();
    }else{
        fillTable();
    }
});
